// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
window.addEventListener("keydown", function(event) {
  // Bind to both command (for Mac) and control (for Win/Linux)
  var modifier = event.ctrlKey || event.metaKey;
  if (modifier && event.shiftKey) {
	if (prevUrl && event.keyCode == 188) {		// '<'
		chrome.extension.sendRequest({redirect: prevUrl});
	}
	else if (nextUrl && event.keyCode == 190) {	// '>'
		chrome.extension.sendRequest({redirect: nextUrl});
	}
  }
}, false);

// djuna
// playxp
// pgr21
// androidpub
// torrentdown : 제대로 안됨
// torrentrg
// google
// naver
// daum
// teamliquid

var prevUrl, nextUrl;

function findLinks() {
	var pageDictionary = {};
	var tags = document.getElementsByTagName("a");
	var i = 0;
	var pageNumbers = [];
	var currentUrl = location.href.split("?")[0];
	for (i = 0; i < tags.length; ++i) {
		var str = tags[i].text.trim();
		var matched = tags[i].text.trim().match(/^[?\[0-9]+\]?$/);	// 1 or [1]
		if (matched && !tags[i].innerHTML.match(/reply|replies/i)	// reply 가 아닌 걸린 경우, http://djuna.cine21.com/xe/?mid=board&page=1
			&& location.href != tags[i].href.replace(/(#\w*)$/,'')) {	// 현재 페이지로 링크 걸린 경우 제외
			// 현재 url 을 포함하거나 링크에 page 포함
			if (tags[i].href.indexOf(currentUrl) == 0 || tags[i].href.match(/(page=[0-9]+|start=[0-9]+)/)) {
				var pageNumber = parseInt(matched[0].match(/[0-9]+/)[0]);
				if (pageDictionary.hasOwnProperty(pageNumber) == false ) {	// 링크가 중복되면 처음 것만 저장
					pageDictionary[pageNumber] = tags[i].href;
					pageNumbers.push(pageNumber);
				}
			}
		}
	}
	
	if (pageNumbers.length < 2)
		return;
	
	pageNumbers.sort(function (a, b) { return a - b; });
	console.log(pageNumbers);

	var prevPageNumber = pageNumbers[0];
	
	for (i = 1; i < pageNumbers.length; ++i) {
		if (pageNumbers[i] != prevPageNumber + 1) {
			prevUrl = pageDictionary[prevPageNumber];
			nextUrl = pageDictionary[pageNumbers[i]];
			return;
		}
		prevPageNumber = pageNumbers[i];
	}
	
	if (pageNumbers[0] == 2) {
		nextUrl = pageDictionary[2];
		return;
	}
}

findLinks();
